package net.mihome.app;


import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroupManager;
import com.easemob.chatuidemo.Constant;
import com.easemob.chatuidemo.db.UserCacheDao;
import com.easemob.chatuidemo.db.UserDao;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.HanziToPinyin;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.utils.StorageUtils;

import net.mihome.app.api.ApiClient;
import net.mihome.app.bean.ActiveList;
import net.mihome.app.bean.AdvertList;
import net.mihome.app.bean.Article;
import net.mihome.app.bean.Banner;
import net.mihome.app.bean.Barcode;
import net.mihome.app.bean.BlogCommentList;
import net.mihome.app.bean.BlogList;
import net.mihome.app.bean.ChatMsgEntity;
import net.mihome.app.bean.ChatRoom;
import net.mihome.app.bean.CommentList;
import net.mihome.app.bean.CommunityList;
import net.mihome.app.bean.FavoriteList;
import net.mihome.app.bean.FriendList;
import net.mihome.app.bean.MessageList;
import net.mihome.app.bean.MyInformation;
import net.mihome.app.bean.News;
import net.mihome.app.bean.NewsList;
import net.mihome.app.bean.NewsType;
import net.mihome.app.bean.Notice;
import net.mihome.app.bean.Post;
import net.mihome.app.bean.PostList;
import net.mihome.app.bean.Report;
import net.mihome.app.bean.Result;
import net.mihome.app.bean.RssNews;
import net.mihome.app.bean.RssResource;
import net.mihome.app.bean.RssType;
import net.mihome.app.bean.SearchList;
import net.mihome.app.bean.Shop;
import net.mihome.app.bean.ShopMenu;
import net.mihome.app.bean.Software;
import net.mihome.app.bean.SoftwareCatalogList;
import net.mihome.app.bean.SoftwareList;
import net.mihome.app.bean.Tweet;
import net.mihome.app.bean.TweetList;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.User;
import net.mihome.app.bean.UserInformation;
import net.mihome.app.bean.UserPrepertie;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.common.ImageUtils;
import net.mihome.app.common.MethodsCompat;
import net.mihome.app.common.StringUtils;
import net.mihome.app.common.UIHelper;
import net.mihome.app.utils.LoginResponseHandler;
import net.mihome.app.utils.MD5;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.RequestParamsFactory;

import org.apache.http.Header;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 全局应用程序类：用于保存和调用全局应用配置及访问网络数据
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class AppContext extends Application {
	public LocationClient mLocationClient;
	public MyLocationListener mMyLocationListener;
	public static final AsyncHttpClient ASYNC_HTTP_CLIENT =new AsyncHttpClient();
    public static final SyncHttpClient SYNC_HTTP_CLIENT=new SyncHttpClient();
	public static final int NETTYPE_WIFI = 0x01;
	public static final int NETTYPE_CMWAP = 0x02;
	public static final int NETTYPE_CMNET = 0x03;
	public static final String TAG="yunbatuisong.....";
	public static final int PAGE_SIZE = 20;//默认分页大小
	private static final int CACHE_TIME = 60*60000;//缓存失效时间
//	public Handler chatHandler;
    private ExecutorService executorService = Executors.newFixedThreadPool(5);


    public static Context applicationContext;
    private static AppContext instance;
	private boolean login = false;	//登录状态
	private int loginUid = 0;	//登录用户的id
    private boolean isLogined=false; //20150408 定义的是否登陆标志。只是用于标记application是重新启动的，还是休眠唤醒的.

    /**
     * 当前用户nickname,为了苹果推送不是userid而是昵称
     */
    public static String currentUserNick = "";
	private Hashtable<String, Object> memCacheRegion = new Hashtable<String, Object>();
	
	private String saveImagePath;//保存图片路径
	
	private Handler unLoginHandler = new Handler(){
		public void handleMessage(Message msg) {
			if(msg.what == 1){
				UIHelper.ToastMessage(AppContext.this, getString(R.string.msg_login_error));
				UIHelper.showLoginDialog(AppContext.this);
			}
		}		
	};
    /**
     * 设计为每次application启动的时候就去加载好友列表，同时将isLogined设为true
     * */
    public void intentToLoadContactList(LoginResponseHandler loginResponseHandler){
        isLogined=true;
        loadContractList2(this,loginResponseHandler);
    }
    /**
     * 获取isLogined变量的值
     * */
    public boolean getIsLogined(){
        return this.isLogined;
    }
    public static MiHomeHXSDKHelper hxSDKHelper = new MiHomeHXSDKHelper();
	@Override
	public void onCreate() {
		super.onCreate();
        applicationContext = this;
        instance = this;
        //注册App异常崩溃处理器
        Thread.setDefaultUncaughtExceptionHandler(AppException.getAppExceptionHandler());
        mLocationClient = new LocationClient(this.getApplicationContext());
		mMyLocationListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mMyLocationListener);
        mLocationClient = new LocationClient(this.getApplicationContext());
        init();
        if(!hxSDKHelper.onInit(this)){
            UIHelper.showAlertDialog(this,"提示","聊天服务初始化失败，请检查网络后重新启动",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    System.exit(0);
                }
            });
        }else{
//            Toast.makeText(this,"聊天服务初始化成功!",Toast.LENGTH_SHORT).show();
        }
	}
	/**
	 * 初始化
	 */
	private void init(){
		
		//初始化httpclient
		PersistentCookieStore persistentCookieStore=new PersistentCookieStore(this);
		ASYNC_HTTP_CLIENT.setCookieStore(persistentCookieStore);
		ASYNC_HTTP_CLIENT.setTimeout(20000);
		ASYNC_HTTP_CLIENT.setConnectTimeout(20000);
        ASYNC_HTTP_CLIENT.setThreadPool(executorService);
		String tokenString=getProperty("cookie");
		ASYNC_HTTP_CLIENT.addHeader("Cookie", tokenString);
		//设置保存图片的路径
		saveImagePath = getProperty(AppConfig.SAVE_IMAGE_PATH);
		if(StringUtils.isEmpty(saveImagePath)){
			setProperty(AppConfig.SAVE_IMAGE_PATH, AppConfig.DEFAULT_SAVE_IMAGE_PATH);
			saveImagePath = AppConfig.DEFAULT_SAVE_IMAGE_PATH;
		}
		initImageLoader(this);
	}
	
	public class MyLocationListener implements BDLocationListener{
		@Override
		public void onReceiveLocation(BDLocation arg0) {
			// TODO Auto-generated method stub
			Log.d("mylocation", ""+arg0.getLatitude());
		}

		@Override
		public void onReceivePoi(BDLocation arg0) {
			// TODO Auto-generated method stub
			
		}
		
	}
	
	/**
	 * 检测当前系统声音是否为正常模式
	 * @return
	 */
	public boolean isAudioNormal() {
		AudioManager mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE); 
		return mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
	}
	
	/**
	 * 应用程序是否发出提示音
	 * @return
	 */
	public boolean isAppSound() {
		return isAudioNormal() && isVoice();
	}
	
	/**
	 * 检测网络是否可用
	 * @return
	 */
	public boolean isNetworkConnected() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		return ni != null && ni.isConnectedOrConnecting();
	}

	/**
	 * 获取当前网络类型
	 * @return 0：没有网络   1：WIFI网络   2：WAP网络    3：NET网络
	 */
	public int getNetworkType() {
		int netType = 0;
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType;
		}		
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			String extraInfo = networkInfo.getExtraInfo();
			if(!StringUtils.isEmpty(extraInfo)){
				if (extraInfo.toLowerCase().equals("cmnet")) {
					netType = NETTYPE_CMNET;
				} else {
					netType = NETTYPE_CMWAP;
				}
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = NETTYPE_WIFI;
		}
		return netType;
	}
	
	/**
	 * 判断当前版本是否兼容目标版本的方法
	 * @param VersionCode
	 * @return
	 */
	public static boolean isMethodsCompat(int VersionCode) {
		int currentVersion = android.os.Build.VERSION.SDK_INT;
		return currentVersion >= VersionCode;
	}
	
	/**
	 * 获取App安装包信息
	 * @return
	 */
	public PackageInfo getPackageInfo() {
		PackageInfo info = null;
		try { 
			info = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {    
			e.printStackTrace(System.err);
		} 
		if(info == null) info = new PackageInfo();
		return info;
	}
	
	/**
	 * 获取App唯一标识
	 * @return
	 */
	public String getAppId() {
		String uniqueID = getProperty(AppConfig.CONF_APP_UNIQUEID);
		if(StringUtils.isEmpty(uniqueID)){
			uniqueID = UUID.randomUUID().toString();
			setProperty(AppConfig.CONF_APP_UNIQUEID, uniqueID);
		}
		return uniqueID;
	}
	
	/**
	 * 用户是否登录
	 * @return
	 */
	public boolean isLogin() {
		return login;
	}
	
	/**
	 * 获取登录用户id
	 * @return
	 */
	public int getLoginUid() {
		return this.loginUid;
	}
	
	/**
	 * 用户注销
	 */
	public void Logout() {
		ApiClient.cleanCookie();
		this.cleanCookie();
		this.login = false;
		this.loginUid = 0;
	}
	
	/**
	 * 未登录或修改密码后的处理
	 */
	public Handler getUnLoginHandler() {
		return this.unLoginHandler;
	}
	
	/**
	 * 初始化用户登录信息
	 */
	public void initLoginInfo() {
		User loginUser = getLoginInfo();
		if(loginUser!=null && loginUser.getUid()>0 && loginUser.isRememberMe()){
			this.loginUid = loginUser.getUid();
			this.login = true;
		}else{
			this.Logout();
		}
	}
	/**
	 * 根据cookie判断用户是否曾经登陆过,如果有token，则表示登陆过
	 * */
	public boolean checkLogin(){
		String appCookie = getProperty("cookie");
		if(appCookie==null){
			return false;
		}else{
			this.login=true;
			return true;
		}
	}
    /**
     * 从缓存中,如果有token，则表示登陆过()
     * */
    public User checkLogin(boolean isHuanxin){
        User user=new User();
        String name=getProperty("user.name");
        String pwd=getProperty("user.pwd");
        String appCookie = getProperty("cookie");
        String openId = getProperty("user.open_id");
        if(appCookie==null||name==null||pwd==null||openId==null){
            return null;
        }else{
            user.setName(name);
            user.setPwd(pwd);
            user.setOpenId(openId);
            return user;
        }
    }
    /**
     * 用户登录验证
     * @param account
     * @param pwd
	 * @return
	 * @throws AppException
	 */
	public User loginVerify(String account, String pwd) throws AppException {
		return ApiClient.login(this, account, pwd);
	}
	
	/**
	 * 我的个人资料
	 * @param isRefresh 是否主动刷新
	 * @return
	 * @throws AppException
	 */
	public MyInformation getMyInformation(boolean isRefresh) throws AppException {
		MyInformation myinfo = null;
		String key = "myinfo_"+loginUid;
//		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			if(isNetworkConnected()) {
			try{
				myinfo = ApiClient.myInformation(this, loginUid);
//				if(myinfo != null && myinfo.getName().length() > 0){
//					Notice notice = myinfo.getNotice();
//					myinfo.setNotice(null);
//					myinfo.setCacheKey(key);
//					saveObject(myinfo, key);
//					myinfo.setNotice(notice);
//				}
			}catch(AppException e){
				myinfo = (MyInformation)readObject(key);
				if(myinfo == null)
					throw e;
			}
		} else {
			myinfo = (MyInformation)readObject(key);
			if(myinfo == null)
				myinfo = new MyInformation();
		}
		return myinfo;
	}	
	/**
	 * 我的个人资料
	 * @param isRefresh 是否主动刷新
	 * @return
	 * @throws AppException
	 */
	public void getMyInformation(boolean isRefresh,MiAsyncHttpResponseHandler<Map> miAsyncHttpResponseHandler)  {
        User user=getLoginInfo();
        if(user!=null){
            ApiClient.myInformation(this, user.getUid(),miAsyncHttpResponseHandler);
        }else {
            Toast.makeText(this,"请重新登陆",Toast.LENGTH_SHORT).show();
        }
	}
    /**
     * 我的个人资料
     * @return
     * @throws AppException
     */
    public void updateUser(String itemName,String itemValue,MiAsyncHttpResponseHandler<Map> miAsyncHttpResponseHandler)  {
            ApiClient.updateUser(this, itemName, itemValue, miAsyncHttpResponseHandler);
    }
    /**
     * 我的个人资料
     * @return
     * @throws AppException
     */
    public void getFriendInformation(int uid,String userName,MiAsyncHttpResponseHandler<Map> miAsyncHttpResponseHandler)  {
        ApiClient.friendInformation(this, uid,userName,miAsyncHttpResponseHandler);
    }
    /**
	 * 获取用户信息个人专页（包含该用户的动态信息以及个人信息）
	 * @param uid 自己的uid
	 * @param hisuid 被查看用户的uid
	 * @param hisname 被查看用户的用户名
	 * @param pageIndex 页面索引
	 * @return
	 * @throws AppException
	 */
	public UserInformation getInformation(int uid, int hisuid, String hisname, int pageIndex, boolean isRefresh) throws AppException {
		String _hisname = ""; 
		if(!StringUtils.isEmpty(hisname)){
			_hisname = hisname;
		}
		UserInformation userinfo = null;
		String key = "userinfo_"+uid+"_"+hisuid+"_"+(URLEncoder.encode(hisname))+"_"+pageIndex+"_"+PAGE_SIZE; 
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {			
			try{
				userinfo = ApiClient.information(this, uid, hisuid, _hisname, pageIndex, PAGE_SIZE);
				if(userinfo != null && pageIndex == 0){
					Notice notice = userinfo.getNotice();
					userinfo.setNotice(null);
					userinfo.setCacheKey(key);
					saveObject(userinfo, key);
					userinfo.setNotice(notice);
				}
			}catch(AppException e){
				userinfo = (UserInformation)readObject(key);
				if(userinfo == null)
					throw e;
			}
		} else {
			userinfo = (UserInformation)readObject(key);
			if(userinfo == null)
				userinfo = new UserInformation();
		}
		return userinfo;
	}
	
	/**
	 * 更新用户之间关系（加关注、取消关注）
	 * @param uid 自己的uid
	 * @param hisuid 对方用户的uid
	 * @param newrelation 0:取消对他的关注 1:关注他
	 * @return
	 * @throws AppException
	 */
	public Result updateRelation(int uid, int hisuid, int newrelation) throws AppException {
		return ApiClient.updateRelation(this, uid, hisuid, newrelation);
	}
	
	/**
	 * 更新用户头像
	 * @param portrait 新上传的头像
	 * @return
	 * @throws AppException
	 */
	public Result updatePortrait(File portrait) throws AppException {
		return ApiClient.updatePortrait(this, loginUid, portrait);
	}
	
	/**
	 * 清空通知消息
	 * @param uid
	 * @param type 1:@我的信息 2:未读消息 3:评论个数 4:新粉丝个数
	 * @return
	 * @throws AppException
	 */
	public Result noticeClear(int uid, int type) throws AppException {
		return ApiClient.noticeClear(this, uid, type);
	}
	
	/**
	 * 获取用户通知信息
	 * @param uid
	 * @return
	 * @throws AppException
	 */
	public Notice getUserNotice(int uid) throws AppException {
		return ApiClient.getUserNotice(this, uid);
	}
	
	/**
	 * 用户收藏列表
	 * @param type 0:全部收藏 1:软件 2:话题 3:博客 4:新闻 5:代码
	 * @param pageIndex 页面索引 0表示第一页
	 * @return
	 * @throws AppException
	 */
	public FavoriteList getFavoriteList(int type, int pageIndex, boolean isRefresh) throws AppException {
		FavoriteList list = null;
		String key = "favoritelist_"+loginUid+"_"+type+"_"+pageIndex+"_"+PAGE_SIZE; 
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				list = ApiClient.getFavoriteList(this, loginUid, type, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (FavoriteList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (FavoriteList)readObject(key);
			if(list == null)
				list = new FavoriteList();
		}
		return list;
	}
	
	/**
	 * 用户粉丝、关注人列表
	 * @param relation 0:显示自己的粉丝 1:显示自己的关注者
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public FriendList getFriendList(int relation, int pageIndex, boolean isRefresh) throws AppException {
		FriendList list = null;
		String key = "friendlist_"+loginUid+"_"+relation+"_"+pageIndex+"_"+PAGE_SIZE; 
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				list = ApiClient.getFriendList(this, loginUid, relation, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (FriendList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (FriendList)readObject(key);
			if(list == null)
				list = new FriendList();
		}
		return list;
	}
	
	/**
	 * 新闻列表
	 * @param catalog
	 * @param pageIndex
	 * @return
	 */
	public NewsList getNewsList(int catalog, int pageIndex, boolean isRefresh) throws AppException {
		NewsList list = null;
		String key = "newslist_"+catalog+"_"+pageIndex+"_"+PAGE_SIZE;
		if(isNetworkConnected()) {
			try{
				list = ApiClient.getNewsList(this, catalog, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (NewsList)readObject(key);
				if(list == null)
					throw e;
			}		
		} else {
			list = (NewsList)readObject(key);
			if(list == null)
				list = new NewsList();
		}
		return list;
	}
	/**
	 * 新闻列表
	 */
	public List<NewsType> getNewsTypeList(int begin,int num) throws AppException {
		List<NewsType> list = new ArrayList<NewsType>();
		if(isNetworkConnected()) {
			try{
				list = ApiClient.getNewsTypeList(this, begin, num);
			}catch(AppException e){
				if(list == null)
					throw e;
			}		
		}
		return list;
	}
	
	/**
	 * 重置密码
	 */
	public boolean resetPassWord(String phone,String passWord) throws AppException {
		if(isNetworkConnected()) {
			try{
				return  ApiClient.resetPassWord(this, phone, passWord);
			}catch(AppException e){
				e.printStackTrace();
				return false;
			}		
		}else{
			return false;
		}
	}
	/**
	 * 根据用户名找手机号
	 */
	public String getPhoneByUsername(String username) throws AppException {
		if(isNetworkConnected()) {
			try{
				return  ApiClient.getPhoneByUsername(this, username);
			}catch(AppException e){
				e.printStackTrace();
				return null;
			}		
		}else{
			return null;
		}
	}
	/**
	 * 新闻列表
	 */
	public NewsList getNewsList2(int typeId, int begin,int num) throws AppException {
		NewsList list = null;
		if(isNetworkConnected()){
			list = ApiClient.getNewsList2(this, typeId, begin, num);
		}else{
			throw AppException.network(new Exception("网络异常"));
		}
		return list;
	}
	public List<ShopMenu> getShopMenus(int shop_id, int begin,int num) throws AppException {
		List<ShopMenu> lShopMenus=null;
		if(isNetworkConnected()){
			lShopMenus = ApiClient.getShopMenus(this, shop_id, begin, num);
		}else{
			throw AppException.network(new Exception("网络异常"));
		}
		return lShopMenus;
	}
	public AdvertList getAdvertList2(int begin,int num) throws AppException {
		AdvertList list = null;
		if(isNetworkConnected()){
			list = ApiClient.getAdvertList2(this,  begin, num);
		}else{
			throw AppException.network(new Exception("网络异常"));
		}
		return list;
	}
	/**
	 * 文章列表
	 */
	public List<Article> getArticleList(int typeId, int begin,int num,String title) throws AppException {
		List<Article> list = null;
		if(isNetworkConnected()){
			list = ApiClient.getArticleList(this, typeId, begin, num,title);
		}else{
			throw AppException.network(new Exception("网络异常"));
		}
		return list;
	}
	/**
	 * 文章详情
	 */
	public Article getArticleDetail(int articleId) throws AppException {
		Article article = null;
		if(isNetworkConnected()){
			article = ApiClient.getArticleDetail(this, articleId);
		}else{
			throw AppException.network(new Exception("网络异常"));
		}
		return article;
	}
	/**
	 * 新闻列表
	 */
	public NewsList getRoomList(int catalog, int pageIndex, boolean isRefresh) throws AppException {
		NewsList list = null;
		String key = "newslist_"+catalog+"_"+pageIndex+"_"+PAGE_SIZE;
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				list = ApiClient.getNewsList(this, catalog, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (NewsList)readObject(key);
				if(list == null)
					throw e;
			}		
		} else {
			list = (NewsList)readObject(key);
			if(list == null)
				list = new NewsList();
		}
		return list;
	}
	/**
	 * 获取rss新闻列表
	 */
	public List<RssNews> getRssNewsList(RssResource rssResource,int pageIndex,int pageSize) throws AppException {
		List<RssNews> list=new ArrayList<RssNews>();
		if(isNetworkConnected()) {
			list=ApiClient.getRssNewsList(this, rssResource, pageIndex, pageSize);
		}
		return list;
	}
	/**
	 * 获取聊天房间列表
	 */
	public List<ChatMsgEntity> getChatRecordList(int room_id,int begin,int num) throws AppException {
		List<ChatMsgEntity> list=new ArrayList<ChatMsgEntity>();
		if(isNetworkConnected()) {
			list=ApiClient.getChatRecordList(this, room_id, begin, num);
		}
		return list;
	}
	/**
	 * 获取聊天记录
	 */
	public List<ChatRoom> getChatRoomList(int begin,int num,int type) throws AppException {
		List<ChatRoom> list=new ArrayList<ChatRoom>();
		if(isNetworkConnected()) {
			list=ApiClient.getChatRoomList(this,  begin, num,type);
		}
		return list;
	}
	/**
	 * 新建聊天房间
	 */
	public ResponsePojo addChatRoom(String name,String desc,String time,String peopel_num ) throws AppException {
		ResponsePojo responsePojo=new ResponsePojo();
		responsePojo.setStatus(-101);
		if(isNetworkConnected()) {
			responsePojo=ApiClient.addChatRoom(this, name, desc, time, peopel_num);
			if(responsePojo.getStatus()<0){
				throw AppException.network(new Exception());
			}
		}
		return responsePojo;
	}
	/**
	 * 新建聊天房间
	 */
	public ResponsePojo JoinRoom(String room_id) throws AppException {
		ResponsePojo responsePojo=new ResponsePojo();
		responsePojo.setStatus(-101);
		if(isNetworkConnected()) {
			responsePojo=ApiClient.joinRoom(this,room_id);
			if(responsePojo.getStatus()<0){
				throw AppException.network(new Exception());
			}
		}
		return responsePojo;
	}
	public ResponsePojo delRoom(String room_id) throws AppException {
		ResponsePojo responsePojo=new ResponsePojo();
		responsePojo.setStatus(-101);
		if(isNetworkConnected()) {
			responsePojo=ApiClient.delRoom(this,room_id);
			if(responsePojo.getStatus()<0){
				throw AppException.network(new Exception());
			}
		}
		return responsePojo;
	}
	public ResponsePojo leavelRoom(String room_id) throws AppException {
		ResponsePojo responsePojo=new ResponsePojo();
		responsePojo.setStatus(-101);
		if(isNetworkConnected()) {
			responsePojo=ApiClient.leavelRoom(this,room_id);
			if(responsePojo.getStatus()<0){
				throw AppException.network(new Exception());
			}
		}
		return responsePojo;
	}
	/**
	 * 设置用户属性到服务器上
	 */
	public void setUserPropertie(String key,String value) {
		if(isNetworkConnected()) {
			try {
				ApiClient.setUserPropertie(this, key, value);
				return;
			} catch (AppException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		setProperty(key, value);
	}
	/**
	 * 获取用户属性
	 */
	public String getUserPropertie(String key) {
		if(isNetworkConnected()) {
			try{
				UserPrepertie userPrepertie= ApiClient.getUserPropertie(this, key);
				if(userPrepertie!=null){
					return userPrepertie.getUvalue();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return getProperty(key);
	}
	/**
	 * 聊天发言
	 */
	public List<ChatMsgEntity> addTalk(String userName,int room_id,String content) throws AppException {
		List<ChatMsgEntity> chatMsgEntities=new ArrayList<ChatMsgEntity>();
		if(isNetworkConnected()) {
			chatMsgEntities=ApiClient.addTalk(this, userName, room_id, content);
		}
		return chatMsgEntities;
	}
	/**
	 * 获取区域列表
	 */
	public CommunityList getAreaList(int parentid) throws AppException {
		CommunityList list = null;
		if(isNetworkConnected()) {
			try{
				list = ApiClient.getArea(this, parentid);
			}catch(AppException e){
				if(list == null)
					throw e;
			}		
		} else {
			throw AppException.network(new Exception("网络故障"));
		}
		return list;
	}
	/**
	 * 资讯列表  by zhao
	 */
	public NewsList getNewsListZhao(int catalog, int pageIndex, boolean isRefresh) throws AppException {
		NewsList list = null;
		String key = "newslist_"+catalog+"_"+pageIndex+"_"+PAGE_SIZE;
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				list = ApiClient.getNewsList(this, catalog, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (NewsList)readObject(key);
				if(list == null)
					throw e;
			}		
		} else {
			list = (NewsList)readObject(key);
			if(list == null)
				list = new NewsList();
		}
		return list;
	}
	
	/**
	 * 新闻详情
	 */
	public News getNews(int news_id, boolean isRefresh) throws AppException {		
		News news = null;
		String key = "news_"+news_id;
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				news = ApiClient.getNewsDetail(this, news_id);
				if(news != null){
					Notice notice = news.getNotice();
					news.setNotice(null);
					news.setCacheKey(key);
					saveObject(news, key);
					news.setNotice(notice);
				}
			}catch(AppException e){
				news = (News)readObject(key);
				if(news == null)
					throw e;
			}
		} else {
			news = (News)readObject(key);
			if(news == null)
				news = new News();
		}
		return news;		
	}
	/**
	 * 发送短信验证码(注册用，手机号已存在则发送失败)
	 * @return
	 */
	public ResponsePojo sendMsgCode(String phoneNum) throws AppException {
		ResponsePojo responsePojo=null;
		if(isNetworkConnected()) 
		{
			try{
                return ApiClient.sendPhoneMsg(this, phoneNum);
			}catch(AppException e){
					throw e;
			}
		} else {
			return null;
		}
	}
    /**
     * 发送短信验证码(注册用，手机号已存在则发送失败)
     * @return
     */
    public ResponsePojo sendMsgCodeExists(String phoneNum) throws AppException {
        ResponsePojo responsePojo=null;
        if(isNetworkConnected())
        {
            try{
                return ApiClient.sendPhoneMsgExists(this, phoneNum);
            }catch(AppException e){
                throw e;
            }
        } else {
            return null;
        }
    }
	/**
	 * 检查用户名是否可用
	 */
	public boolean checkUserName(String userName) throws AppException {		
		ResponsePojo responsePojo=null;
		if(isNetworkConnected()) 
		{
			try{
				responsePojo = ApiClient.checkUserName(this, userName);
				if(responsePojo.getStatus()<0){
					return false;
				}else{
					return true; //返回true时可用
				}
			}catch(AppException e){
					throw e;
			}
		} else {
			return false;
		}
	}
	/**
	 *注册
	 */
	public boolean register(String username ,String mobile  ,String password ,String community_id,String buildingid  ) throws AppException {
		ResponsePojo responsePojo=null;
		if(isNetworkConnected()) 
		{
			try{
				responsePojo = ApiClient.register(this,username ,mobile  ,password ,community_id,buildingid  );
				if(responsePojo.getStatus()<0){
					return false;
				}else{
					return true; //返回true时可用
				}
			}catch(AppException e){
					throw e;
			}
		} else {
			return false;
		}
	}
	/**
	 * 发送短信验证码
	 * @return
	 */
	public ResponsePojo checkCode(String mobile,String num) throws AppException {
		ResponsePojo responsePojo=null;
		if(isNetworkConnected()) 
		{
			try{
				responsePojo = ApiClient.checkPhoneMsg(this,mobile,num);
				return responsePojo;
			}catch(AppException e){
					throw e;
			}
		} else {
			return responsePojo;
		}
	}
	/**
	 * 商店详情
	 */
	public Shop getShopDetail(int shop_id) throws AppException {		
		Shop shop = null;
		String key = "shop_"+shop_id;
		if(isNetworkConnected() && (!isReadDataCache(key))) {
			try{
				shop = ApiClient.getShopDetail(this, shop_id);
			}catch(AppException e){
				shop = (Shop)readObject(key);
				if(shop == null)
					throw e;
			}
		} else {
			shop = (Shop)readObject(key);
			if(shop == null)
				shop = new Shop();
		}
		return shop;		
	}
	/**
	 * 用户博客列表
	 * @param authoruid
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public BlogList getUserBlogList(int authoruid, String authorname, int pageIndex, boolean isRefresh) throws AppException {
		BlogList list = null;
		String key = "userbloglist_"+authoruid+"_"+(URLEncoder.encode(authorname))+"_"+loginUid+"_"+pageIndex+"_"+PAGE_SIZE;
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				list = ApiClient.getUserBlogList(this, authoruid, authorname, loginUid, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (BlogList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (BlogList)readObject(key);
			if(list == null)
				list = new BlogList();
		}
		return list;
	}
	
	/**
	 * 博客列表
	 * @param type 推荐：recommend 最新：latest
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public BlogList getBlogList(String type, int pageIndex, boolean isRefresh) throws AppException {
		BlogList list = null;
		String key = "bloglist_"+type+"_"+pageIndex+"_"+PAGE_SIZE;
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				list = ApiClient.getBlogList(this, type, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (BlogList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (BlogList)readObject(key);
			if(list == null)
				list = new BlogList();
		}
		return list;
	}
	
	/**
	 * 博客详情
	 * @param blog_id
	 * @return
	 * @throws AppException
	 */
	public RssType getBlog(int blog_id, boolean isRefresh) throws AppException {
		RssType blog = null;
		String key = "blog_"+blog_id;
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				blog = ApiClient.getBlogDetail(this, blog_id);
				if(blog != null){
					Notice notice = blog.getNotice();
					blog.setNotice(null);
					blog.setCacheKey(key);
					saveObject(blog, key);
					blog.setNotice(notice);
				}
			}catch(AppException e){
				blog = (RssType)readObject(key);
				if(blog == null)
					throw e;
			}
		} else {
			blog = (RssType)readObject(key);
			if(blog == null)
				blog = new RssType();
		}
		return blog;
	}
	
	/**
	 * 软件列表
	 * @param searchTag 软件分类  推荐:recommend 最新:time 热门:view 国产:list_cn
	 * @return
	 * @throws AppException
	 */
	public SoftwareList getSoftwareList(String searchTag, int pageIndex, boolean isRefresh) throws AppException {
		SoftwareList list = null;
		String key = "softwarelist_"+searchTag+"_"+pageIndex+"_"+PAGE_SIZE;
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				list = ApiClient.getSoftwareList(this, searchTag, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (SoftwareList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (SoftwareList)readObject(key);
			if(list == null)
				list = new SoftwareList();
		}
		return list;
	}
	
	/**
	 * 软件分类的软件列表
	 * @return
	 * @throws AppException
	 */
	public SoftwareList getSoftwareTagList(int searchTag, int pageIndex, boolean isRefresh) throws AppException {
		SoftwareList list = null;
		String key = "softwaretaglist_"+searchTag+"_"+pageIndex+"_"+PAGE_SIZE;
		if(isNetworkConnected() && (isCacheDataFailure(key) || isRefresh)) {
			try{
				list = ApiClient.getSoftwareTagList(this, searchTag, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (SoftwareList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (SoftwareList)readObject(key);
			if(list == null)
				list = new SoftwareList();
		}
		return list;
	}
	
	/**
	 * 软件分类列表
	 * @param tag 第一级:0  第二级:tag
	 * @return
	 * @throws AppException
	 */
	public SoftwareCatalogList getSoftwareCatalogList(int tag) throws AppException {
		SoftwareCatalogList list = null;
		String key = "softwarecataloglist_"+tag;
		if(isNetworkConnected() && isCacheDataFailure(key)) {
			try{
				list = ApiClient.getSoftwareCatalogList(this, tag);
				if(list != null){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (SoftwareCatalogList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (SoftwareCatalogList)readObject(key);
			if(list == null)
				list = new SoftwareCatalogList();
		}
		return list;
	}
	
	/**
	 * 软件详情
	 * @return
	 * @throws AppException
	 */
	public Software getSoftware(String ident, boolean isRefresh) throws AppException {
		Software soft = null;
		String key = "software_"+(URLEncoder.encode(ident));
		if(isNetworkConnected() && (isCacheDataFailure(key) || isRefresh)) {
			try{
				soft = ApiClient.getSoftwareDetail(this, ident);
				if(soft != null){
					Notice notice = soft.getNotice();
					soft.setNotice(null);
					soft.setCacheKey(key);
					saveObject(soft, key);
					soft.setNotice(notice);
				}
			}catch(AppException e){
				soft = (Software)readObject(key);
				if(soft == null)
					throw e;
			}
		} else {
			soft = (Software)readObject(key);
			if(soft == null)
				soft = new Software();
		}
		return soft;
	}
	/**
	 * 帖子列表
	 */
	public PostList getRepairReauestList(int begin,int num) throws AppException {
		PostList list = null;
		if(isNetworkConnected()) {		
			try{
				list = ApiClient.getRepairReauestList(this, begin, num);
			}catch(AppException e){
				if(list == null)
					throw e;
			}
		} else {
				list = new PostList();
		}
		return list;
	}
	/**
	 * 帖子列表
	 * @param catalog
	 * @param pageIndex
	 * @return
	 */
	public PostList getPostList(int catalog, int pageIndex, boolean isRefresh) throws AppException {
		PostList list = null;
		String key = "postlist_"+catalog+"_"+pageIndex+"_"+PAGE_SIZE;
		if(isNetworkConnected()) {		
			try{
				list = ApiClient.getPostList(this, catalog, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (PostList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (PostList)readObject(key);
			if(list == null)
				list = new PostList();
		}
		return list;
	}
	
	/**
	 * Tag相关帖子列表
	 * @param tag
	 * @param pageIndex
	 * @return
	 */
	public PostList getPostListByTag(String tag, int pageIndex, boolean isRefresh) throws AppException {
		PostList list = null;
		String key = "postlist_"+(URLEncoder.encode(tag))+"_"+pageIndex+"_"+PAGE_SIZE;
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {		
			try{
				list = ApiClient.getPostListByTag(this, tag, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (PostList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (PostList)readObject(key);
			if(list == null)
				list = new PostList();
		}
		return list;
	}
	
	/**
	 * 读取帖子详情
	 * @param post_id
	 * @return
	 */
	public Post getPost(int post_id, boolean isRefresh) throws AppException {		
		Post post = null;
		String key = "post_"+post_id;
		if(isNetworkConnected()) {	
			try{
				post = ApiClient.getPostDetail(this, post_id);
				if(post != null){
					Notice notice = post.getNotice();
					post.setNotice(null);
					post.setCacheKey(key);
					saveObject(post, key);
					post.setNotice(notice);
				}
			}catch(AppException e){
				post = (Post)readObject(key);
				if(post == null)
					throw e;
			}
		} else {
			post = (Post)readObject(key);
			if(post == null)
				post = new Post();
		}
		return post;		
	}
	
	/**
	 * 动弹列表
	 * @param catalog -1 热门，0 最新，大于0 某用户的动弹(uid)
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public TweetList getTweetList(int catalog, int pageIndex, boolean isRefresh) throws AppException {
		TweetList list = null;
        User user=getLoginInfo();
        int communityId=-1;
        if(user!=null&&user.getCommunityId()!=null){
            communityId=user.getCommunityId();
        }
		String key = "tweetlist_"+catalog+"_"+pageIndex+"_"+PAGE_SIZE;		
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				list = ApiClient.getTweetList(this, catalog,communityId,pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (TweetList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (TweetList)readObject(key);
			if(list == null)
				list = new TweetList();
		}
		return list;
	}
	/**
	 * 新闻列表
	 */
	public TweetList getTweetList2(int typeId, int begin,int num) throws AppException {
		TweetList list = null;
		if(isNetworkConnected()){
			list = ApiClient.getTweetList2(this, typeId, begin, num);
		}else{
			throw AppException.network(new Exception("网络异常"));
		}
		return list;
	}
	/**
	 * 新闻列表
	 */
	public void getTweetListAsync(int typeId, int begin,int num,MiAsyncHttpResponseHandler asyncHttpResponseHandler){
        User user=getLoginInfo();
        int communityId=-1;
        if(user!=null&&user.getCommunityId()!=null){
            communityId=user.getCommunityId();
        }
		ApiClient.getTweetListAnsy(this, typeId, user.getUid(),communityId,begin, num, asyncHttpResponseHandler);
	}
    /**
     * 顶大字报
     * */
    public void supportTweetAsync(int bigpaperId,MiAsyncHttpResponseHandler asyncHttpResponseHandler){
        Integer uid=getLoginInfo().getUid();
        String userName=getLoginInfo().getName();
        if(uid==null){
            Long timeMillis=System.currentTimeMillis();
            uid=timeMillis.intValue();
        }
        ApiClient.supportTweetAnsy(this, uid,userName,bigpaperId, asyncHttpResponseHandler);
    }
    /**
     * 删除大字报
     * */
    public void deleteBigPaper(int bigpaperId,MiAsyncHttpResponseHandler asyncHttpResponseHandler){
        Integer uid=getLoginInfo().getUid();
        if(uid==null){
            Long timeMillis=System.currentTimeMillis();
            uid=timeMillis.intValue();
        }
        ApiClient.deleteBigPaper(this,bigpaperId, asyncHttpResponseHandler);
    }
	/**
	 * 获取动弹详情
	 * @param tweet_id
	 * @return
	 * @throws AppException
	 */
	public Tweet getTweet(int tweet_id, boolean isRefresh) throws AppException {
		Tweet tweet = null;
		String key = "tweet_"+tweet_id;
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				tweet = ApiClient.getTweetDetail(this, tweet_id);
				if(tweet != null){
					Notice notice = tweet.getNotice();
					tweet.setNotice(null);
					tweet.setCacheKey(key);
					saveObject(tweet, key);
					tweet.setNotice(notice);
				}
			}catch(AppException e){
				tweet = (Tweet)readObject(key);
				if(tweet == null)
					throw e;
			}
		} else {
			tweet = (Tweet)readObject(key);
			if(tweet == null)
				tweet = new Tweet();
		}
		return tweet;
	}
	
	/**
	 * 动态列表
	 * @param catalog 1最新动态 2@我 3评论 4我自己
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public ActiveList getActiveList(int catalog, int pageIndex, boolean isRefresh) throws AppException {
		ActiveList list = null;
		String key = "activelist_"+loginUid+"_"+catalog+"_"+pageIndex+"_"+PAGE_SIZE;
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				list = ApiClient.getActiveList(this, loginUid, catalog, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (ActiveList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (ActiveList)readObject(key);
			if(list == null)
				list = new ActiveList();
		}
		return list;
	}
	/**
	 * 广告列表
	 * @param catalog 1最新动态 2@我 3评论 4我自己
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public AdvertList getAdvertList(int catalog, int pageIndex, boolean isRefresh) throws AppException {
		AdvertList list = null;
		String key = "advertlist"+loginUid+"_"+catalog+"_"+pageIndex+"_"+PAGE_SIZE;
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				list = ApiClient.getAdvertList(this, loginUid, catalog, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (AdvertList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (AdvertList)readObject(key);
			if(list == null)
				list = new AdvertList();
		}
		return list;
	}
	
	/**
	 * 留言列表
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public MessageList getMessageList(int pageIndex, boolean isRefresh) throws AppException {
		MessageList list = null;
		String key = "messagelist_"+loginUid+"_"+pageIndex+"_"+PAGE_SIZE;
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				list = ApiClient.getMessageList(this, loginUid, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (MessageList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (MessageList)readObject(key);
			if(list == null)
				list = new MessageList();
		}
		return list;
	}
	
	/**
	 * 博客评论列表
	 * @param id 博客Id
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public BlogCommentList getBlogCommentList(int id, int pageIndex, boolean isRefresh) throws AppException {
		BlogCommentList list = null;
		String key = "blogcommentlist_"+id+"_"+pageIndex+"_"+PAGE_SIZE;		
		if(isNetworkConnected() && (!isReadDataCache(key) || isRefresh)) {
			try{
				list = ApiClient.getBlogCommentList(this, id, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (BlogCommentList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (BlogCommentList)readObject(key);
			if(list == null)
				list = new BlogCommentList();
		}
		return list;
	}
	
	/**
	 * 评论列表
	 * @param catalog 1新闻 2帖子 3动弹 4动态
	 * @param id 某条新闻，帖子，动弹的id 或者某条留言的friendid
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public CommentList getCommentList(int catalog, int id, int pageIndex, boolean isRefresh) throws AppException {
		CommentList list = null;
		String key = "commentlist_"+catalog+"_"+id+"_"+pageIndex+"_"+PAGE_SIZE;		
		if(isNetworkConnected()) {
			try{
				list = ApiClient.getCommentList(this, catalog, id, pageIndex, PAGE_SIZE);
				if(list != null && pageIndex == 0){
					Notice notice = list.getNotice();
					list.setNotice(null);
					list.setCacheKey(key);
					saveObject(list, key);
					list.setNotice(notice);
				}
			}catch(AppException e){
				list = (CommentList)readObject(key);
				if(list == null)
					throw e;
			}
		} else {
			list = (CommentList)readObject(key);
			if(list == null)
				list = new CommentList();
		}
		return list;
	}
	
	/**
	 * 获取搜索列表
	 * @param catalog 全部:all 新闻:news  问答:post 软件:software 博客:blog 代码:code
	 * @param content 搜索的内容
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public SearchList getSearchList(String catalog, String content, int pageIndex, int pageSize) throws AppException {
		return ApiClient.getSearchList(this, catalog, content, pageIndex, pageSize);
	}
	
	/**
	 * 发帖子
	 * @param post （uid、title、catalog、content、isNoticeMe）
	 * @return
	 * @throws AppException
	 */
	public Result pubPost(Post post) throws AppException {
		return ApiClient.pubPost(this, post);
	}
	
	/**
	 * 发动弹
	 * @return
	 * @throws AppException
	 */
	public Result pubTweet(Tweet tweet) throws AppException {
		return ApiClient.pubTweet(this, tweet);
	}
	/**
	 * 发动弹
	 * @return
	 * @throws AppException
	 */
	public Result pubBaoxiu(Tweet tweet) throws AppException {
		return ApiClient.pubBaoxiu(this, tweet);
	}
	/**
	 * 删除动弹
	 * @param uid
	 * @param tweetid
	 * @return
	 * @throws AppException
	 */
	public Result delTweet(int uid, int tweetid) throws AppException {
		return ApiClient.delTweet(this, uid, tweetid);
	}
	
	/**
	 * 发送留言
	 * @param uid 登录用户uid
	 * @param receiver 接受者的用户id
	 * @param content 消息内容，注意不能超过250个字符
	 * @return
	 * @throws AppException
	 */
	public Result pubMessage(int uid, int receiver, String content) throws AppException {
		return ApiClient.pubMessage(this, uid, receiver, content);
	}
	
	/**
	 * 转发留言
	 * @param uid 登录用户uid
	 * @param receiver 接受者的用户名
	 * @param content 消息内容，注意不能超过250个字符
	 * @return
	 * @throws AppException
	 */
	public Result forwardMessage(int uid, String receiver, String content) throws AppException {
		return ApiClient.forwardMessage(this, uid, receiver, content);
	}
	
	/**
	 * 删除留言
	 * @param uid 登录用户uid
	 * @param friendid 留言者id
	 * @return
	 * @throws AppException
	 */
	public Result delMessage(int uid, int friendid) throws AppException {
		return ApiClient.delMessage(this, uid, friendid);
	}
	
	/**
	 * 发表评论
	 * @param catalog 1新闻  2帖子  3动弹  4动态
	 * @param id 某条新闻，帖子，动弹的id
	 * @param uid 用户uid
	 * @param content 发表评论的内容
	 * @param isPostToMyZone 是否转发到我的空间  0不转发  1转发
	 * @return
	 * @throws AppException
	 */
	public Result pubComment(int catalog, int id, int uid, String content, int isPostToMyZone) throws AppException {
		return ApiClient.pubComment(this, catalog, id, uid, content, isPostToMyZone);
	}
	
	/**
	 * 
	 * @param id 表示被评论的某条新闻，帖子，动弹的id 或者某条消息的 friendid 
	 * @param catalog 表示该评论所属什么类型：1新闻  2帖子  3动弹  4动态
	 * @param replyid 表示被回复的单个评论id
	 * @param authorid 表示该评论的原始作者id
	 * @param uid 用户uid 一般都是当前登录用户uid
	 * @param content 发表评论的内容
	 * @return
	 * @throws AppException
	 */
	public Result replyComment(int id, int catalog, int replyid, int authorid, int uid, String content) throws AppException {
		return ApiClient.replyComment(this, id, catalog, replyid, authorid, uid, content);
	}
	
	/**
	 * 删除评论
	 * @param id 表示被评论对应的某条新闻,帖子,动弹的id 或者某条消息的 friendid
	 * @param catalog 表示该评论所属什么类型：1新闻  2帖子  3动弹  4动态&留言
	 * @param replyid 表示被回复的单个评论id
	 * @param authorid 表示该评论的原始作者id
	 * @return
	 * @throws AppException
	 */
	public Result delComment(int id, int catalog, int replyid, int authorid) throws AppException {
		return ApiClient.delComment(this, id, catalog, replyid, authorid);
	}
	
	/**
	 * 发表博客评论
	 * @param blog 博客id
	 * @param uid 登陆用户的uid
	 * @param content 评论内容
	 * @return
	 * @throws AppException
	 */
	public Result pubBlogComment(int blog, int uid, String content) throws AppException {
		return ApiClient.pubBlogComment(this, blog, uid, content);
	}
	
	/**
	 * 发表博客评论
	 * @param blog 博客id
	 * @param uid 登陆用户的uid
	 * @param content 评论内容
	 * @param reply_id 评论id
	 * @param objuid 被评论的评论发表者的uid
	 * @return
	 * @throws AppException
	 */
	public Result replyBlogComment(int blog, int uid, String content, int reply_id, int objuid) throws AppException {
		return ApiClient.replyBlogComment(this, blog, uid, content, reply_id, objuid);
	}
	
	/**
	 * 删除博客评论
	 * @param uid 登录用户的uid
	 * @param blogid 博客id
	 * @param replyid 评论id
	 * @param authorid 评论发表者的uid
	 * @param owneruid 博客作者uid
	 * @return
	 * @throws AppException
	 */
	public Result delBlogComment(int uid, int blogid, int replyid, int authorid, int owneruid) throws AppException {
		return ApiClient.delBlogComment(this, uid, blogid, replyid, authorid, owneruid);
	}
	
	/**
	 * 删除博客
	 * @param uid 登录用户的uid
	 * @param authoruid 博客作者uid
	 * @param id 博客id
	 * @return
	 * @throws AppException
	 */
	public Result delBlog(int uid, int authoruid, int id) throws AppException { 	
		return ApiClient.delBlog(this, uid, authoruid, id);
	}
	
	/**
	 * 举报讨论区帖子
	 * @param report
	 * @return
	 * @throws AppException
	 */
	public String report(Report report) throws AppException {
		return ApiClient.report(this, report);
	}
	
	/**
	 * 扫描二维码签到
	 * @param barcode
	 * @return
	 * @throws AppException
	 */
	public String signIn(Barcode barcode) throws AppException{
		return ApiClient.signIn(this, barcode);
	}
	
	/**
	 * 用户添加收藏
	 * @param uid 用户UID
	 * @param objid 比如是新闻ID 或者问答ID 或者动弹ID
	 * @param type 1:软件 2:话题 3:博客 4:新闻 5:代码
	 * @return
	 * @throws AppException
	 */
	public Result addFavorite(int uid, int objid, int type) throws AppException {
		return ApiClient.addFavorite(this, uid, objid, type);
	}
	
	/**
	 * 用户删除收藏
	 * @param uid 用户UID
	 * @param objid 比如是新闻ID 或者问答ID 或者动弹ID
	 * @param type 1:软件 2:话题 3:博客 4:新闻 5:代码
	 * @return
	 * @throws AppException
	 */
	public Result delFavorite(int uid, int objid, int type) throws AppException { 	
		return ApiClient.delFavorite(this, uid, objid, type);
	}
	
	/**
	 * 保存登录信息
	 */
	public void saveLoginInfo(final User user) {
		this.loginUid = user.getUid();
		this.login = true;
		setProperties(new Properties(){{
			setProperty("user.uid", String.valueOf(user.getUid()));
			setProperty("user.name", user.getName());
			setProperty("user.real_name", (user.getRealName()!=null)?user.getRealName():user.getName());
			setProperty("user.face", user.getFace()+"");//用户头像-文件名
			setProperty("user.account", user.getAccount()+"");
			setProperty("user.token", user.getToken());
			setProperty("user.open_id", user.getOpenId());
			setProperty("user.token", user.getToken());
			setProperty("user.community_name", user.getCommunityName()+"");
			setProperty("user.community_id", user.getCommunityId()+"");
//			setProperty("user.pwd", MD5.Md5(user.getPwd()).toUpperCase());
			setProperty("user.pwd", user.getPwd());
//			setProperty("user.location", user.getLocation());
//			setProperty("user.followers", String.valueOf(user.getFollowers()));
//			setProperty("user.fans", String.valueOf(user.getFans()));
//			setProperty("user.score", String.valueOf(user.getScore()));
//			setProperty("user.isRememberMe", String.valueOf(user.isRememberMe()));//是否记住我的信息
		}});		
	}
	
	/**
	 * 清除登录信息
	 */
	public void cleanLoginInfo() {
		this.loginUid = 0;
		this.login = false;
		removeProperty("user.uid","user.name","user.face","user.account","user.pwd",
				"user.location","user.followers","user.fans","user.score","user.isRememberMe");
	}
	
	/**
	 * 获取登录信息
	 * @return
	 */
	public User getLoginInfo() {		
		User lu = new User();		
		lu.setUid(StringUtils.toInt(getProperty("user.uid"), 0));
		lu.setName(getProperty("user.name"));
		lu.setRealName(getProperty("user.real_name"));
		lu.setFace(getProperty("user.face"));
		lu.setToken(getProperty("user.token"));
		lu.setAccount(getProperty("user.account"));
		lu.setPwd(getProperty("user.pwd"));
		lu.setOpenId(getProperty("user.open_id"));
		lu.setLocation(getProperty("user.location"));
        lu.setCommunityName(getProperty("user.community_name"));
        String communityIdstr=getProperty("user.community_id");
        if(communityIdstr!=null){
            Integer communityId=Integer.parseInt(communityIdstr);
            lu.setCommunityId(communityId);
        }
		return lu;
	}
	
	/**
	 * 保存用户头像
	 * @param fileName
	 * @param bitmap
	 */
	public void saveUserFace(String fileName,Bitmap bitmap) {
		try {
			ImageUtils.saveImage(this, fileName, bitmap);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取用户头像
	 * @param key
	 * @return
	 * @throws AppException
	 */
	public Bitmap getUserFace(String key) throws AppException {
		FileInputStream fis = null;
		try{
			fis = openFileInput(key);
			return BitmapFactory.decodeStream(fis);
		}catch(Exception e){
			throw AppException.run(e);
		}finally{
			try {
				fis.close();
			} catch (Exception e) {}
		}
	}
	
	/**
	 * 是否加载显示文章图片
	 * @return
	 */
	public boolean isLoadImage()
	{
		String perf_loadimage = getProperty(AppConfig.CONF_LOAD_IMAGE);
		//默认是加载的
		if(StringUtils.isEmpty(perf_loadimage))
			return true;
		else
			return StringUtils.toBool(perf_loadimage);
	}
	
	/**
	 * 设置是否加载文章图片
	 * @param b
	 */
	public void setConfigLoadimage(boolean b)
	{
		setProperty(AppConfig.CONF_LOAD_IMAGE, String.valueOf(b));
	}
	
	/**
	 * 是否发出提示音
	 * @return
	 */
	public boolean isVoice()
	{
		String perf_voice = getProperty(AppConfig.CONF_VOICE);
		//默认是开启提示声音
		if(StringUtils.isEmpty(perf_voice))
			return true;
		else
			return StringUtils.toBool(perf_voice);
	}
	
	/**
	 * 设置是否发出提示音
	 * @param b
	 */
	public void setConfigVoice(boolean b)
	{
		setProperty(AppConfig.CONF_VOICE, String.valueOf(b));
	}
	
	/**
	 * 是否启动检查更新
	 * @return
	 */
	public boolean isCheckUp()
	{
		String perf_checkup = getProperty(AppConfig.CONF_CHECKUP);
		//默认是开启
		if(StringUtils.isEmpty(perf_checkup))
			return true;
		else
			return StringUtils.toBool(perf_checkup);
	}
	
	/**
	 * 设置启动检查更新
	 * @param b
	 */
	public void setConfigCheckUp(boolean b)
	{
		setProperty(AppConfig.CONF_CHECKUP, String.valueOf(b));
	}
	
	/**
	 * 是否左右滑动
	 * @return
	 */
	public boolean isScroll()
	{
		String perf_scroll = getProperty(AppConfig.CONF_SCROLL);
		//默认是关闭左右滑动
		if(StringUtils.isEmpty(perf_scroll))
			return false;
		else
			return StringUtils.toBool(perf_scroll);
	}
	
	/**
	 * 设置是否左右滑动
	 * @param b
	 */
	public void setConfigScroll(boolean b)
	{
		setProperty(AppConfig.CONF_SCROLL, String.valueOf(b));
	}
	
	/**
	 * 是否Https登录
	 * @return
	 */
	public boolean isHttpsLogin()
	{
		String perf_httpslogin = getProperty(AppConfig.CONF_HTTPS_LOGIN);
		//默认是http
		if(StringUtils.isEmpty(perf_httpslogin))
			return false;
		else
			return StringUtils.toBool(perf_httpslogin);
	}
	
	/**
	 * 设置是是否Https登录
	 * @param b
	 */
	public void setConfigHttpsLogin(boolean b)
	{
		setProperty(AppConfig.CONF_HTTPS_LOGIN, String.valueOf(b));
	}
	
	/**
	 * 清除保存的缓存
	 */
	public void cleanCookie()
	{
		removeProperty(AppConfig.CONF_COOKIE);
	}
	
	/**
	 * 判断缓存数据是否可读
	 * @param cachefile
	 * @return
	 */
	private boolean isReadDataCache(String cachefile)
	{
		return readObject(cachefile) != null;
	}
	
	/**
	 * 判断缓存是否存在
	 * @param cachefile
	 * @return
	 */
	private boolean isExistDataCache(String cachefile)
	{
		boolean exist = false;
		File data = getFileStreamPath(cachefile);
		if(data.exists())
			exist = true;
		return exist;
	}
	
	/**
	 * 判断缓存是否失效
	 * @param cachefile
	 * @return
	 */
	public boolean isCacheDataFailure(String cachefile)
	{
		boolean failure = false;
		File data = getFileStreamPath(cachefile);
		if(data.exists() && (System.currentTimeMillis() - data.lastModified()) > CACHE_TIME)
			failure = true;
		else if(!data.exists())
			failure = true;
		return failure;
	}
	
	/**
	 * 清除app缓存
	 */
	public void clearAppCache()
	{
		//清除webview缓存
//		File file = CacheManager.getCacheFileBaseDir();  
//		if (file != null && file.exists() && file.isDirectory()) {  
//		    for (File item : file.listFiles()) {  
//		    	item.delete();  
//		    }  
//		    file.delete();  
//		}  		  
		deleteDatabase("webview.db");  
		deleteDatabase("webview.db-shm");  
		deleteDatabase("webview.db-wal");  
		deleteDatabase("webviewCache.db");  
		deleteDatabase("webviewCache.db-shm");  
		deleteDatabase("webviewCache.db-wal");  
		//清除数据缓存
		clearCacheFolder(getFilesDir(),System.currentTimeMillis());
		clearCacheFolder(getCacheDir(),System.currentTimeMillis());
		//2.2版本才有将应用缓存转移到sd卡的功能
		if(isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)){
			clearCacheFolder(MethodsCompat.getExternalCacheDir(this),System.currentTimeMillis());
		}
		//清除编辑器保存的临时内容
		Properties props = getProperties();
		for(Object key : props.keySet()) {
			String _key = key.toString();
			if(_key.startsWith("temp"))
				removeProperty(_key);
		}
	}	
	
	/**
	 * 清除缓存目录
	 * @param dir 目录
	 * @return
	 */
	private int clearCacheFolder(File dir, long curTime) {          
	    int deletedFiles = 0;         
	    if (dir!= null && dir.isDirectory()) {             
	        try {                
	            for (File child:dir.listFiles()) {    
	                if (child.isDirectory()) {              
	                    deletedFiles += clearCacheFolder(child, curTime);          
	                }  
	                if (child.lastModified() < curTime) {     
	                    if (child.delete()) {                   
	                        deletedFiles++;           
	                    }    
	                }    
	            }             
	        } catch(Exception e) {       
	            e.printStackTrace();    
	        }     
	    }       
	    return deletedFiles;     
	}
	
	/**
	 * 将对象保存到内存缓存中
	 * @param key
	 * @param value
	 */
	public void setMemCache(String key, Object value) {
		memCacheRegion.put(key, value);
	}
	
	/**
	 * 从内存缓存中获取对象
	 * @param key
	 * @return
	 */
	public Object getMemCache(String key){
		return memCacheRegion.get(key);
	}
	
	/**
	 * 保存磁盘缓存
	 * @param key
	 * @param value
	 * @throws IOException
	 */
	public void setDiskCache(String key, String value) throws IOException {
		FileOutputStream fos = null;
		try{
			fos = openFileOutput("cache_"+key+".data", Context.MODE_PRIVATE);
			fos.write(value.getBytes());
			fos.flush();
		}finally{
			try {
				fos.close();
			} catch (Exception e) {}
		}
	}
	
	/**
	 * 获取磁盘缓存数据
	 * @param key
	 * @return
	 * @throws IOException
	 */
	public String getDiskCache(String key) throws IOException {
		FileInputStream fis = null;
		try{
			fis = openFileInput("cache_"+key+".data");
			byte[] datas = new byte[fis.available()];
			fis.read(datas);
			return new String(datas);
		}finally{
			try {
				fis.close();
			} catch (Exception e) {}
		}
	}
	
	/**
	 * 保存对象
	 * @param ser
	 * @param file
	 * @throws IOException
	 */
	public boolean saveObject(Serializable ser, String file) {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try{
			fos = openFileOutput(file, MODE_PRIVATE);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(ser);
			oos.flush();
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}finally{
			try {
				oos.close();
			} catch (Exception e) {}
			try {
				fos.close();
			} catch (Exception e) {}
		}
	}
	
	/**
	 * 读取对象
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public Serializable readObject(String file){
		if(!isExistDataCache(file))
			return null;
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try{
			fis = openFileInput(file);
			ois = new ObjectInputStream(fis);
			return (Serializable)ois.readObject();
		}catch(FileNotFoundException e){
		}catch(Exception e){
			e.printStackTrace();
			//反序列化失败 - 删除缓存文件
			if(e instanceof InvalidClassException){
				File data = getFileStreamPath(file);
				data.delete();
			}
		}finally{
			try {
				ois.close();
			} catch (Exception e) {}
			try {
				fis.close();
			} catch (Exception e) {}
		}
		return null;
	}

	public boolean containsProperty(String key){
		Properties props = getProperties();
		 return props.containsKey(key);
	}
	
	public void setProperties(Properties ps){
		AppConfig.getAppConfig(this).set(ps);
	}

	public Properties getProperties(){
		return AppConfig.getAppConfig(this).get();
	}
	
	public void setProperty(String key,String value){
		AppConfig.getAppConfig(this).set(key, value);
	}
	
	public String getProperty(String key){
		return AppConfig.getAppConfig(this).get(key);
	}
	public void removeProperty(String...key){
		AppConfig.getAppConfig(this).remove(key);
	}

	/**
	 * 获取内存中保存图片的路径
	 * @return
	 */
	public String getSaveImagePath() {
		return saveImagePath;
	}
	/**
	 * 设置内存中保存图片的路径
	 * @return
	 */
	public void setSaveImagePath(String saveImagePath) {
		this.saveImagePath = saveImagePath;
	}	
	// 创建HttpClient实例
		private HttpClient createHttpClient() {
			HttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params,
					HTTP.DEFAULT_CONTENT_CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, true);
			HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
			HttpConnectionParams.setSoTimeout(params, 20 * 1000);
			HttpConnectionParams.setSocketBufferSize(params, 8192);
			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schReg.register(new Scheme("https",
					SSLSocketFactory.getSocketFactory(), 443));

			ClientConnectionManager connMgr = new ThreadSafeClientConnManager(
					params, schReg);

			return new DefaultHttpClient(connMgr, params);
		}

		private HttpClient httpClient;
		// 关闭连接管理器并释放资源
		private void shutdownHttpClient() {
			if (httpClient != null && httpClient.getConnectionManager() != null) {
				httpClient.getConnectionManager().shutdown();
			}
		}
		/**
		 * 获取banner图
		 * */
		public  Banner getBanner() throws AppException{
				return ApiClient.getBanner(this);
		}
		// 对外提供HttpClient实例
		public HttpClient getHttpClient() {
			return httpClient;
		}
		public static void initImageLoader(Context context) { 
			 		// This configuration tuning is custom. You can tune every option, you may tune some of them, 
			 		// or you can create default configuration by 
			 		//  ImageLoaderConfiguration.createDefault(this); 
			 		// method.
            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.default_image)
                    .showImageForEmptyUri(R.drawable.ic_menu_about) // resource or drawable
                    .showImageOnFail(R.drawable.ic_menu_about) // resource or drawable
                    .resetViewBeforeLoading(false)  // default
                    .cacheInMemory(false) // default
                    .cacheOnDisk(true) // default
                    .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
                    .bitmapConfig(Bitmap.Config.ARGB_8888) // default
                    .displayer(new SimpleBitmapDisplayer()) // default
                    .handler(new Handler()) // default
                    .build();
			File cacheDir = StorageUtils.getCacheDirectory(context);
			 		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
			 				.threadPriority(Thread.NORM_PRIORITY - 2)
			 				.denyCacheImageMultipleSizesInMemory() 
			 				.diskCacheFileNameGenerator(new Md5FileNameGenerator())
			 				.diskCache(new UnlimitedDiscCache(cacheDir)) // default
			 				.diskCacheSize(50 * 1024 * 1024) // 50 Mb 
			 				.tasksProcessingOrder(QueueProcessingType.LIFO) 
			 				.writeDebugLogs() // Remove for release app
                            .defaultDisplayImageOptions(options)
			 				.build();
			 		// Initialize ImageLoader with configuration. 
			 		ImageLoader.getInstance().init(config);
			 	}
    public static AppContext getInstance() {
        return instance;
    }
    /**
     * 获取内存中好友user list
     *
     * @return
     */
    public Map<String, User> getContactList() {
        return hxSDKHelper.getContactList();
    }

    /**
     * 设置好友user list到内存中
     *
     * @param contactList
     */
    public void setContactList(Map<String, User> contactList) {
        hxSDKHelper.setContactList(contactList);
    }

    /**
     * 获取当前登陆用户名
     *
     * @return
     */
    public String getUserName() {
        return hxSDKHelper.getHXId();
    }

    /**
     * 获取密码
     *
     * @return
     */
    public String getPassword() {
        return hxSDKHelper.getPassword();
    }

    /**
     * 设置用户名
     *
     */
    public void setUserName(String username) {
        hxSDKHelper.setHXId(username);
    }

    /**
     * 设置密码 下面的实例代码 只是demo，实际的应用中需要加password 加密后存入 preference 环信sdk
     * 内部的自动登录需要的密码，已经加密存储了
     *
     * @param pwd
     */
    public void setPassword(String pwd) {
        hxSDKHelper.setPassword(pwd);
    }

    /**
     * 退出登录,清空数据
     */
    public void logout(final EMCallBack emCallBack) {
        // 先调用sdk logout，在清理app中自己的数据
        hxSDKHelper.logout(emCallBack);
    }
    /**
     * 用于登录成功之后从环信服务器上获取用户列表  by zhao
     * */
    public void loadContractList(final LoginResponseHandler loginResponseHandler){
        isLogined=true;
        RequestParams requestParams= RequestParamsFactory.newInstance(this);
        User user=AppContext.getInstance().getLoginInfo();
        requestParams.add("open_id",user.getOpenId());
        ASYNC_HTTP_CLIENT.get(this, URLs.MIHOME_USER_CHAT_LIST_FRIENDS, requestParams, new MiAsyncHttpResponseHandler<List<Map>>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<List<Map>> responsePojo) {
                try {
                    List<User> list = User.parserList(responsePojo);
                    String currentName = EMChatManager.getInstance().getCurrentUser();
                    EMGroupManager.getInstance().loadAllGroups();
                    EMChatManager.getInstance().loadAllConversations();
                    Iterator<User> iterator = list.iterator();
                    Map<String, User> userlist = new HashMap<String, User>();
                    while (iterator.hasNext()) {
                        User user = iterator.next();
                        setUserHearder(user.getName(), user);
                        userlist.put(user.getName(), user);
                    }
                    // 添加user"申请与通知"
                    User newFriends = new User();
                    newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
                    newFriends.setNick("新邻居");
                    newFriends.setHeader("");
                    userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends);
                    // 添加"圈子"
                    User groupUser = new User();
                    groupUser.setUsername(Constant.CONTACT_LIST_BLACK_LIST);
                    groupUser.setNick("黑名单");
                    groupUser.setHeader("");
                    userlist.put(Constant.CONTACT_LIST_BLACK_LIST, groupUser);

                    // 存入内存
                    AppContext.getInstance().setContactList(userlist);
                    // 存入db
                    UserDao dao = new UserDao(AppContext.getInstance());
                    List<User> users = new ArrayList<User>(userlist.values());
                    dao.saveContactList(users);
                    EMGroupManager.getInstance().getGroupsFromServer();
                    loginResponseHandler.onSuccess(null);
                } catch (EaseMobException e) {
                    e.printStackTrace();
                    loginResponseHandler.onFailed(e.getMessage());
                }
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                loginResponseHandler.onFailed(arg3.getMessage());
            }
        });
    }
    /**
     * 用于登录成功之后从环信服务器上获取用户列表  by zhao
     * */
    public void loadContractList2(Context context,final LoginResponseHandler loginResponseHandler){
        isLogined=true;
        RequestParams requestParams=RequestParamsFactory.newInstance(this);
        User user=AppContext.getInstance().getLoginInfo();
        requestParams.add("open_id",user.getOpenId());
        ASYNC_HTTP_CLIENT.get(context, URLs.MIHOME_USER_CHAT_LIST_FRIENDS, requestParams, new MiAsyncHttpResponseHandler<List<Map>>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<List<Map>> responsePojo) {
                try {
                    List<User> list = User.parserList(responsePojo);
                    String currentName = EMChatManager.getInstance().getCurrentUser();
                    EMGroupManager.getInstance().loadAllGroups();
                    EMChatManager.getInstance().loadAllConversations();
                    Iterator<User> iterator = list.iterator();
                    Map<String, User> userlist = new HashMap<String, User>();
                    while (iterator.hasNext()) {
                        User user = iterator.next();
                        setUserHearder(user.getName(), user);
                        userlist.put(user.getName(), user);
                    }
                    // 添加user"申请与通知"
                    User newFriends = new User();
                    newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
                    newFriends.setNick("新邻居");
                    newFriends.setHeader("");
                    userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends);
                    // 添加"圈子"
                    User groupUser = new User();
                    groupUser.setUsername(Constant.CONTACT_LIST_BLACK_LIST);
                    groupUser.setNick("黑名单");
                    groupUser.setHeader("");
                    userlist.put(Constant.CONTACT_LIST_BLACK_LIST, groupUser);

                    // 存入内存
                    AppContext.getInstance().setContactList(userlist);
                    // 存入db
                    UserDao dao = new UserDao(AppContext.getInstance());
                    List<User> users = new ArrayList<User>(userlist.values());
                    dao.saveContactList(users);
                    EMGroupManager.getInstance().getGroupsFromServer();
                    loginResponseHandler.onSuccess(null);
                } catch (EaseMobException e) {
                    e.printStackTrace();
                    loginResponseHandler.onFailed(e.getMessage());
                }
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                loginResponseHandler.onFailed(arg3.getMessage());
            }
        });
    }
    public static void loginAsync(String userName,String pwd,LoginResponseHandler loginResponseHandler){
        ApiClient.loginAsync(AppContext.getInstance(),userName,pwd,loginResponseHandler);
    }
    /**
     * 设置hearder属性，方便通讯中对联系人按header分类显示，以及通过右侧ABCD...字母栏快速定位联系人
     *
     * @param username
     * @param user
     */
    protected void setUserHearder(String username, User user) {
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0, 1)).get(0).target.substring(0, 1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
    }
    /**
     * 密码加密。主要用于环信登录。
     * 登录米宅是将密码明文发给服务器的。但是登录环信需要将密文发给环信。
     * 所以用这个来加密。这个加密方式应该跟米宅服务器端密码加密方式相同。
     * */
    public String encnryPwd(String pwd){
        return  MD5.Md5(pwd).toUpperCase();
    }
    /**
     * 用户名加密。主要用于环信登录。
     * 环信的用户名是通过将米宅用户名md5之后获取的哦啊的
     * */
    public String encnryUserId(String userName){
        return  MD5.Md5(userName).toLowerCase();
    }
    /**
     * 根据openId获取一个用户的基本信息（openid、username、头像等等），用于聊天信息的转换。
     * 该函数首先从数据库中获取，如果数据库中获取不到则从网络获取，然后存入数据库
     * */
    public User getOneUser(final String openId){
        final UserCacheDao userDao=new UserCacheDao(this);
        final User user=userDao.getOne(openId);
        if(user==null){
            RequestParams requestParams=new RequestParams();
            requestParams.add("open_id",openId);
            //给服务器新加一个接口，通过一个openid获取用户的详细信息
            AppContext.ASYNC_HTTP_CLIENT.get(this, URLs.MIHOME_USER_CHAT_GET_USER_BY_OPENID,requestParams,new MiAsyncHttpResponseHandler<Map>() {
                @Override
                public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                    User user2 = User.parse(responsePojo.getData());
                    String showName = user2.getName();
                    if (user2.getRealName() != null && !"".equals(user2.getRealName().trim())) {
                        showName = user2.getRealName();
                    }
                    UserCacheDao userDao2=new UserCacheDao(AppContext.getInstance());
                    userDao2.saveContact(user2);
                    user.setFace(user2.getFace());
                    user.setName(user2.getName());
                    user.setUsername(user2.getUsername());
                    user.setRealName(user2.getRealName());
                    user.setOpenId(user2.getOpenId());
                }
                @Override
                public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                    arg3.printStackTrace();
                    Toast.makeText(AppContext.getInstance(),"获取好友信息失败",Toast.LENGTH_SHORT).show();
                }
            });
        }
        return user;
    }
   public String uploadImage(File file,String name) throws Exception {
       return ApiClient.uploadImage(this,file,name);
   }
    public String uploadImage(File file) throws Exception {
        return ApiClient.uploadImage(this,file);
    }
    /**
     * 获取好友未读消息（不包括群消息）
     * */
    public int getUnReadCountFromFriends(){
        Map<String,User> maps=getContactList();
        int sum=0;
        if(maps!=null){
            Iterator<String> iterator=maps.keySet().iterator();
            while(iterator.hasNext()){
                User user=maps.get(iterator.next());
                if(user.getOpenId()==null){
                    continue;
                }
                try{
                    EMConversation conversation = EMChatManager.getInstance().getConversation(user.getOpenId());
                    sum=sum+conversation.getUnreadMsgCount();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            return sum;
        }else{
            return sum;
        }
    }

    public final static String LAST_BIGPAPER_ID="LAST_BIGPAPER_ID"; //最后一条大字报的key
    /**
     * 用户最后读到的大字报id写到本地
     * */
    public void setLastBigpaper(Long lastBigpaperId){
        if(lastBigpaperId==null){
            lastBigpaperId=0L;
        }
        AppContext.getInstance().setProperty(LAST_BIGPAPER_ID,lastBigpaperId.toString());
    }
    /**
     * 读取用户最后读到的大字报id
     * */
    public Long getLastBigpaper(){
        String lastIdStr=AppContext.getInstance().getProperty(LAST_BIGPAPER_ID);
        Long lastBigpaperId=null;
        if(lastIdStr!=null&&!"".equals(lastIdStr.trim())){
            lastBigpaperId=Long.parseLong(lastIdStr);
        }
        return lastBigpaperId;
    }

 }
